/**
 * Created by no1 on 2015/8/28.
 */
'use strict';
var mysql = require('../mysql.js');
var C = require('../../config/index');
var F = require('../../common/function');
var MPosts = require('../../model/posts.js');
var MTags = require('../../model/tags.js');
var MUser = require('../../model/users.js');
var Mman = require('../../common/man.js');
var imgRule = require('../../common/imgRule.js');
var _ = require('underscore');
var _s = require('underscore.string');
var md5 = require('md5');
var request = require('koa-request');
var async_request = require('request');
var logstash = require('./../logFlow/logstash.js');
_.v = require('validator');

/*
 *@todo  API16 收藏或取消收藏某主题
 * */
exports.fav = function*(Env) {
  let fields = Env.I;
  let loginStatus = fields.loginStatus;
  if (!loginStatus.status) {
    return F.returnMsg(401, '登录用户才能收藏操作', 3);
  }
  var act = fields.act; // 1/11:收藏 2/12:取消收藏
  var tid = fields.tid;
  var uid = loginStatus.uid;

  // 判断帖子是否存在
  var isThreadExist = yield MPosts.isThreadExist(tid);
  if (!isThreadExist) {
    return F.returnMsg(300, '帖子不存在', 3);
  }

  // 是否已经收藏
  var isFav = yield mysql.query('SELECT uid FROM mh_fav WHERE uid=? AND tid=?', [uid, tid]);
  if (act == 1 || act == 11) { //收藏
    if (isFav.length <= 0) {
      // 添加收藏
      result = yield mysql.query('INSERT ignore INTO mh_fav(uid,tid,timeline) VALUES(?,?,UNIX_TIMESTAMP())', [uid, tid]);
      if (result.affectedRows < 1) {
        return F.returnMsg(400, '你已经收藏过这帖子了', 1);
      }
      // 用户收藏帖子数加1
      mysql.query('UPDATE mh_user_info SET tfavtimes=tfavtimes+1 WHERE uid=?', [uid]);
      //更新收藏用户信息开始
      var key = C.redisPre.user_info;
      key = _s.sprintf(key, parseInt(uid));
      var temp = yield F.redisCo.EXISTS(key);
      if (temp == 1) {
        F.redisClient.HINCRBY(key, 'tfavtimes', 1);//用户收藏数+1
      }
      //更新收藏用户信息结束

      //帖子被收藏数加1
      mysql.query('UPDATE mh_thread SET favtimes=favtimes+1 WHERE tid=?', [tid]);
      //更新帖子信息开始
      key = C.redisPre.thread_info;
      key = _s.sprintf(key, parseInt(tid));
      temp = yield F.redisCo.EXISTS(key);
      if (temp == 1) {
        F.redisClient.HINCRBY(key, 'favtimes', 1);//帖子被收藏数+1
      }

      //重新生成用户收藏帖子缓存开始
      key = C.redisPre.user_list;
      key = _.str.sprintf(key, uid, 3);
      temp = yield F.redisCo.EXISTS(key);
      if (temp == 1) {//缓存存在时推进去
        var arr = [];
        arr[0] = key;
        arr.push(F.timestamp());
        arr.push(tid);
        yield F.redisCo.ZADD(arr);
      }
      else {//不存在时重新生成
        yield F.userList(parseInt(uid), 3);
      }
      //重新生成用户收藏帖子缓存结束
      var gain = yield F.generateIntegralLog(uid, 11, tid);//收藏成功后获得积分
    }
    // TODO 插入动态表
    return F.returnMsg(200, {act: '收藏成功', e: gain}, 4, {tid: tid, fav: true});
  }
  else { // 取消收藏
    if (isFav.length > 0) {
      // 删除收藏
      var result = yield mysql.query('DELETE FROM mh_fav WHERE uid=? AND tid=?', [uid, tid]);
      if (result.affectedRows < 1) {
        return F.returnMsg(400, '失败', 1);
      }
      var tfavtimes = yield mysql.queryOne('SELECT tfavtimes FROM mh_user_info WHERE uid=?', [uid]);
      if (parseInt(tfavtimes['tfavtimes']) > 0) {
        // 收藏数减1
        mysql.query('UPDATE mh_user_info SET tfavtimes=tfavtimes-1 WHERE uid=?', [uid]);
        //更新收藏用户信息开始
        var key = C.redisPre.user_info;
        key = _s.sprintf(key, parseInt(uid));
        var temp = yield F.redisCo.EXISTS(key);
        if (temp == 1) {
          F.redisClient.HINCRBY(key, 'tfavtimes', -1);//用户收藏数-1
        }
        //更新收藏用户信息结束
      }
      //帖子被收藏数减1
      mysql.query('UPDATE mh_thread SET favtimes=favtimes-1 WHERE tid=?', [tid]);
      //更新帖子信息开始
      key = C.redisPre.thread_info;
      key = _s.sprintf(key, parseInt(tid));
      temp = yield F.redisCo.EXISTS(key);
      if (temp == 1) {
        F.redisClient.HINCRBY(key, 'favtimes', -1);//帖子被收藏数-1
      }
      //更新帖子信息结束

      //重新生成用户收藏缓存开始
      key = C.redisPre.user_list;
      key = _.str.sprintf(key, uid, 3);
      temp = yield F.redisCo.EXISTS(key);
      if (temp == 1) {
        F.redisClient.ZREM(key, tid);
      }
      //重新生成用户收藏缓存结束
      var gain = yield F.generateIntegralLog(uid, 12, tid);//订阅成功后获得积分
    }
    // TODO 插入动态表
    return F.returnMsg(200, {act: '取消收藏成功', e: gain}, 4, {tid: tid, fav: false});
  }
};
